package de.windeln.marketing.campaign.costinterval.dailyCost.services;

import java.util.Date;

import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.beans.factory.annotation.Required;

import de.windeln.marketing.campaign.costinterval.dailyCost.dao.interfaces.DailyCostMapper;
import de.windeln.marketing.campaign.costinterval.dailyCost.model.DailyCostClientObject;
import de.windeln.marketing.campaign.costinterval.dailyCost.services.interfaces.DailyCostService;
import de.windeln.marketing.campaign.costinterval.model.CostintervalClientObject;
import de.windeln.marketing.utils.RandomNumberGenerator;

public class DefaultDailyCostService implements DailyCostService {

	private DailyCostMapper dailyCostMapper;

	@Override
	public void insertNewDailyCosts(CostintervalClientObject costInterval) {
		DailyCostClientObject dailyCost = new DailyCostClientObject();
		dailyCost.setCampaignId(costInterval.getCampaignId());
		dailyCost.setDailyCost(costInterval.getDailyCost());
		dailyCost.setCostintervalId(costInterval.getId());

		int daysDifference = 1 + Days.daysBetween(new DateTime(costInterval.getCostStart()), new DateTime(costInterval.getCostEnd())).getDays();
		Date currentDate = costInterval.getCostStart();
		while (daysDifference > 0) {
			dailyCost.setId(RandomNumberGenerator.generateRandomUniqueIDAsLong());
			dailyCost.setDayDate(currentDate);
			dailyCostMapper.insertNewDailyCost(dailyCost);
			currentDate = (new DateTime(currentDate).plusDays(1)).toDate();
			System.out.println("Aktuelles Datum:" + currentDate);
			daysDifference--;
		}

	}

	@Override
	public void editDailyCosts(CostintervalClientObject costInterval) {
		dailyCostMapper.updateDailyCostToDeleteState(costInterval.getId());
		// s. insert; allerdings muss ID erhalten bleiben und nicht neu
		// generiert werden -> PROBLEM => Editfunktionalität nicht anbieten
		// TODO
	}

	@Override
	public void deleteDailyCosts(Long costintervalId) {
		dailyCostMapper.updateDailyCostToDeleteState(costintervalId);

	}

	@Required
	public void setDailyCostMapper(DailyCostMapper dailyCostMapper) {
		this.dailyCostMapper = dailyCostMapper;
	}

	@Override
	public void deleteDailyCostsByCampaignId(Long campaignId) {
		dailyCostMapper.updateDailyCostToDeleteStateByCampaignId(campaignId);
		
	}

}
